/* eslint-disable @typescript-eslint/no-shadow */
import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.less'
import Store from '../store'
import { observer, useLocalObservable } from 'mobx-react'
import icon_dui from '@/resource/auction/icon_dui.png'
import icon_cuo from '@/resource/auction/icon_cuo.png'
import icon_no2 from '@/resource/auction/icon_no2.png'
import icon_no3 from '@/resource/auction/icon_no3.png'
import default_avatar from '@/resource/default_avatar.png'
import { sortNum } from '../const'
import { SocketContainer } from '@/hooks/useSocket'
import { Toast } from 'antd-mobile'

let time: any
function Game() {
    const store = useLocalObservable(() => Store)
    const { send, onMessage, remove } = SocketContainer.useContainer()
    const { lot_obj, setData, binding_info, initBindingInfo } = store
    const { binding_result, is_pass } = binding_info || {}
    const [success, setSuccess] = useState(false) // 成交动画
    const [isPass, setIsPass] = useState(is_pass === '1') // 是否pass
    const clickRef = useRef(false)
    const lotObjRef = useRef(lot_obj)

    /** 竞价 */
    function addPrice(price: number) {
        if (clickRef.current) {
            return
        }
        /** 防止连点 */
        clickRef.current = true
        time = setTimeout(() => {
            clickRef.current = false
        }, 1000)
        send('bidding', {
            params: {
                price: Number(binding_result?.[0]?.price || 0) + price,
                lot_id: lot_obj.id,
                is_pass: '0',
            },
        })
    }

    useEffect(() => {
        lotObjRef.current = lot_obj
    }, [lot_obj])
    useEffect(() => {
        document.title = '拍卖游戏'
        /** 监听竞价 */
        function bidding({ data }: any) {
            const { bidding_result: newResult, is_pass, lot_id } = data
            /** pass */
            if (is_pass === '1') {
                setIsPass(true)
            }
            /** 自己竞价时 有is_pass且为0 */
            if (is_pass === '0') {
                Toast.show({
                    content: '竞价成功',
                    icon: 'success',
                    duration: 1000,
                    maskClickable: false,
                })
            }
            /** 设置数据 */
            if (newResult.length === 0) {
                return
            }
            console.log('lot_obj', lot_obj)
            /** 如果商品id对应不上忽略 */
            if (lot_id !== lotObjRef?.current?.id) {
                return
            }
            clickRef.current = false
            setData('binding_info', {
                ...binding_info,
                lot_id,
                binding_result: newResult,
            })
        }

        function step_flow({ data }: any) {
            clickRef.current = false
            if (data.goto === 'game') {
                setSuccess(true)
                setTimeout(() => {
                    setSuccess(() => false)
                }, 1000)
                initBindingInfo()
                setIsPass(false)
            }
        }

        function close({ data }: any) {
            const { bidding_student_num } = data

            setData('binding_info', {
                ...binding_info,
                bidding_student_num,
            })
        }
        /** 断连 */
        onMessage('close', close)
        /** 竞价 */
        onMessage('bidding', bidding)
        /** 切换下一件商品 */
        onMessage('step_flow', step_flow)
        return () => {
            remove('bidding', bidding)
            remove('step_flow', step_flow)
            remove('close', close)
            clearTimeout(time)
        }
    }, [])
    console.log('binding_result', binding_result)

    return (
        <div className={styles.layout_container}>
            <div className={styles.bar} />
            <div className={styles.box}>
                <div className={styles.rank_1}>
                    <div className={styles.avatar_warpper}>
                        <img src={binding_result?.[0]?.avatar || default_avatar} />
                    </div>
                    <div className={styles.info}>
                        <span>{binding_result?.[0]?.name || '--'}</span>
                        <span className={styles.tips}>参与竞价</span>
                    </div>
                    <div className={styles.price}>{binding_result?.[0]?.price || '--'}万</div>
                </div>
                <div className={styles.rank_2}>
                    <img src={icon_no2} />
                    <span className={styles.name}>{binding_result?.[1]?.name || '--'}</span>
                    {/* <span className={styles.tips}>出价</span> */}
                    <span>{binding_result?.[1]?.price || '--'}万</span>
                </div>
                <div className={styles.rank_3}>
                    <img src={icon_no3} />
                    <span className={styles.name}>{binding_result?.[2]?.name || '--'}</span>
                    {/* <span className={styles.tips}>出价</span> */}
                    <span>{binding_result?.[2]?.price || '--'}万</span>
                </div>
            </div>
            <div className={success ? styles.auctionner_success : styles.auctionner} />
            <div className={styles.right_board}>
                <div className={styles.board_title}>拍卖商品{sortNum.split('')[lot_obj?.sort]}</div>
                <div className={styles.board_content}>{lot_obj?.describe}</div>
            </div>
            <div className={styles.price_board}>
                <div className={styles.price_board_top}>
                    剩余可拍金额：<span>{lot_obj?.user_balance}万</span>
                </div>
                <div className={styles.price_board_main}>
                    <div className={styles.main}>
                        {!isPass && lot_obj?.user_balance > 0 && (
                            <>
                                <div
                                    className={styles.price_btn}
                                    onClick={() => {
                                        addPrice(50)
                                    }}
                                >
                                    + 50万
                                </div>
                                <div
                                    className={styles.price_btn}
                                    onClick={() => {
                                        addPrice(100)
                                    }}
                                >
                                    + 100万
                                </div>
                                <div
                                    className={styles.price_btn}
                                    onClick={() => {
                                        addPrice(150)
                                    }}
                                >
                                    + 150万
                                </div>
                                <div
                                    className={styles.price_btn}
                                    onClick={() => {
                                        addPrice(200)
                                    }}
                                >
                                    + 200万
                                </div>
                                <div
                                    className={styles.pass_btn}
                                    onClick={() => {
                                        send('bidding', {
                                            params: {
                                                is_pass: '1',
                                                lot_id: lot_obj.id,
                                            },
                                        })
                                    }}
                                >
                                    Pass（不参拍）
                                </div>
                            </>
                        )}
                        {isPass && (
                            <div className={styles.pass_content}>
                                <div className={styles.img_wrapper}>
                                    <img src={icon_dui} />
                                </div>
                                <span>已Pass（不参拍）该件商品，你还可以参与后续商品竞拍喔~</span>
                            </div>
                        )}
                        {lot_obj?.user_balance === '0' && (
                            <div className={styles.no_money_content}>
                                <div className={styles.img_wrapper}>
                                    <img src={icon_cuo} />
                                </div>
                                <span>你已没有剩余得可拍金额，无法参与后续商品竞拍喔~~</span>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    )
}

export default observer(Game)
